package com.example.wan_android.ui.activity

import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.view.GravityCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.wan_android.BR
import com.example.wan_android.R
import com.example.wan_android.adapter.DrawItemAdapter
import com.example.wan_android.adapter.TabAdapter
import com.example.wan_android.adapter.ViewPagerAdapter
import com.example.wan_android.databinding.ActivityMainBinding
import com.example.wan_android.model.TabItemInfoData
import com.example.wan_android.tools.Sp
import com.example.wan_android.tools.SpacesItemDecoration
import com.example.wan_android.ui.fragment.AuthorFragment
import com.example.wan_android.ui.fragment.PaperShowFragment
import com.example.wan_android.ui.fragment.ProjectFragment
import com.example.wan_android.ui.fragment.SystemFragment
import com.example.wan_android.viewmodel.MainViewModel

class MainActivity : BaseActivity<ActivityMainBinding, MainViewModel>(
    MainViewModel::class.java,
    R.layout.activity_main,
    BR.viewModel
) {

    private val viewPagerAdapter by lazy { ViewPagerAdapter(this) }
    private val tabAdapter by lazy {
        TabAdapter(mViewModel!!)
    }
    private val drawItemAdapter by lazy {
        DrawItemAdapter(mViewModel!!)
    }

    override fun onRestart() {
        super.onRestart()
        val number = Sp.getString(this, "userName", "")
        val password = Sp.getString(this, "password", "")
        mViewModel?.login(number ?: "", password ?: "")
        mViewModel?.isLogin?.observe(this) {
            if (it) {
                mViewDataBinding?.tvLogin?.text = Sp.getString(this, "userName", "登录")
            }
        }
    }

    override fun initView() {
        // 沉浸式状态栏
        ViewCompat.setOnApplyWindowInsetsListener(mViewDataBinding?.llMainContent) { view, insets->
            val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars())

            view.setPadding(0, 0, 0, bars.bottom)
            mViewDataBinding?.flToolBar?.let {
                if (it.paddingTop == 0) {
                    it.setPadding(0, bars.top, 0, 0)
                    it.layoutParams.height += bars.top
                }
            }
            insets
        }

        Sp.getSharedPrefs(this)
        val number = Sp.getString(this, "userName", "")
        val password = Sp.getString(this, "password", "")
        mViewModel?.login(number ?: "", password ?: "")
        mViewDataBinding?.init()
        mViewModel?.indexLiveData?.observe(this) {
            mViewDataBinding?.vpFragment?.currentItem = it
        }
        mViewDataBinding?.rvItem?.adapter = drawItemAdapter
        mViewDataBinding?.rvItem?.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        mViewDataBinding?.rvItem?.addItemDecoration(SpacesItemDecoration(30))
        mViewModel?.isLogin?.observe(this) {
            mViewDataBinding?.tvLogin?.text = Sp.getString(this, "userName", "登录")
        }
        mViewModel?.openDialog?.observe(this) {
            val dialog = AlertDialog.Builder(this)
            if (it) {
                dialog.setMessage("您确定要退出登录吗？")
                    .setPositiveButton("确定") { _, _ ->
                        mViewModel?.exitLogin()
                        Sp.clear(
                            this
                        )
                    }
                    .setNegativeButton("取消") { _, _ ->
                    }
                    .show()
            }
        }

        mViewModel?.isLogin?.observe(this) {
            when (it) {
                true -> {
                    drawItemAdapter.setListData(mViewModel?.drawItemList ?: emptyList())
                }

                false -> {
                    drawItemAdapter.setListData(mViewModel?.noLoginDrawItemList ?: emptyList())
                }
            }

        }
        mViewDataBinding?.ivOpenDrawer?.setOnClickListener({
            mViewDataBinding?.drawLayout?.openDrawer(mViewDataBinding?.dlView!!)
        })

        mViewDataBinding?.drawLayout?.addDrawerListener(object : DrawerLayout.DrawerListener {
            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
                // 根据滑动状态调整主界面交互
                when (mViewDataBinding?.drawLayout?.isDrawerOpen(GravityCompat.START)) {
                    true -> {
                        // 锁定主界面禁止滑动和点击
                        mViewDataBinding?.drawLayout?.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
                        mViewDataBinding?.llMainContent?.isClickable = false
                        mViewDataBinding?.llMainContent?.isFocusable = false
                    }

                    false -> {
                        // 恢复主界面交互
                        mViewDataBinding?.drawLayout?.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
                        mViewDataBinding?.llMainContent?.isClickable = true
                        mViewDataBinding?.llMainContent?.isFocusable = true
                    }

                    else -> Unit
                }
            }

            override fun onDrawerOpened(drawerView: View) {}
            override fun onDrawerClosed(drawerView: View) {}
            override fun onDrawerStateChanged(newState: Int) {}
        })
    }

    private fun ActivityMainBinding.init() {
        listOf(
            PaperShowFragment(),
            SystemFragment(),
            AuthorFragment(),
            ProjectFragment()
        ).forEach {
            viewPagerAdapter.addFragment(it)
        }

        val tabInfo = listOf(
            TabItemInfoData(resources.getString(R.string.main), R.drawable.ic_bottom_bar_home),
            TabItemInfoData(
                resources.getString(R.string.knowledge_body),
                R.drawable.ic_bottom_bar_navi
            ),
            TabItemInfoData(resources.getString(R.string.author), R.drawable.menu_public),
            TabItemInfoData(resources.getString(R.string.project), R.drawable.ic_bottom_bar_ques)
        )

        tabAdapter.setListData(tabInfo)

        mViewDataBinding?.vpFragment?.adapter = viewPagerAdapter
        mViewDataBinding?.vpFragment?.isUserInputEnabled = false
        mViewDataBinding?.rvTab?.adapter = tabAdapter
        mViewDataBinding?.rvTab?.layoutManager =
            GridLayoutManager(this@MainActivity, 4)
    }
}